<template>
  <view class="security-management-page">
    <!-- 导航栏 -->
    <u-navbar title="安保管理" back-icon="arrow-left" />
    
    <!-- 统计卡片区域 -->
    <view class="statistics-section">
      <view class="statistics-card">
        <view class="statistics-item">
          <text class="statistics-value">{{ statistics.totalPatrols || 0 }}</text>
          <text class="statistics-label">巡逻次数</text>
        </view>
        <view class="statistics-item">
          <text class="statistics-value">{{ statistics.completedPatrols || 0 }}</text>
          <text class="statistics-label">已完成</text>
        </view>
        <view class="statistics-item">
          <text class="statistics-value">{{ statistics.totalEvents || 0 }}</text>
          <text class="statistics-label">安全事件</text>
        </view>
        <view class="statistics-item">
          <text class="statistics-value">{{ statistics.pendingEvents || 0 }}</text>
          <text class="statistics-label">待处理</text>
        </view>
      </view>
    </view>

    <!-- 功能入口区域 -->
    <view class="function-section">
      <view class="section-title">功能管理</view>
      
      <!-- 路线管理 -->
      <service-card
        title="路线管理"
        description="管理巡逻路线和检查点"
        icon-name="map"
        theme-color="#3498db"
        @click="goToRouteManagement"
      />
      
      <!-- 巡逻管理 -->
      <service-card
        title="巡逻管理"
        description="执行巡逻任务和签到"
        icon-name="shield"
        theme-color="#2ed573"
        @click="goToPatrolManagement"
      />
      
      <!-- 事件管理 -->
      <service-card
        title="事件管理"
        description="上报和处理安全事件"
        icon-name="alert-circle"
        theme-color="#ff4757"
        @click="goToEventManagement"
      />
      
      <!-- 访客管理 -->
      <service-card
        title="访客管理"
        description="访客登记和离开记录"
        icon-name="user-plus"
        theme-color="#ff9500"
        @click="goToVisitorManagement"
      />
      
      <!-- 统计报表 -->
      <service-card
        title="统计报表"
        description="查看安保工作统计和报表"
        icon-name="bar-chart"
        theme-color="#3742fa"
        @click="goToStatistics"
      />
    </view>

    <!-- 今日巡逻区域 -->
    <view class="today-patrols-section">
      <view class="section-title">
        今日巡逻
        <text class="more-link" @click="goToPatrolManagement">更多 ></text>
      </view>
      
      <view v-if="todayPatrols.length === 0" class="empty-state">
        <u-empty text="今日暂无巡逻任务" icon="shield" mode="list" />
      </view>
      
      <view v-else class="patrol-list">
        <view 
          v-for="patrol in todayPatrols" 
          :key="patrol.id"
          class="patrol-card"
          @click="goToPatrolDetail(patrol.id)"
        >
          <view class="patrol-header">
            <text class="patrol-route">{{ patrol.routeName }}</text>
            <u-tag 
              :text="getStatusText(patrol.status)" 
              :type="getStatusType(patrol.status)" 
              size="mini"
            />
          </view>
          <view class="patrol-content">
            <text class="patrol-time">{{ formatTime(patrol.startTime) }}</text>
            <text class="patrol-duration">{{ getDuration(patrol.startTime, patrol.endTime) }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 紧急事件区域 -->
    <view class="emergency-events-section">
      <view class="section-title">
        紧急事件
        <text class="more-link" @click="goToEventManagement">更多 ></text>
      </view>
      
      <view v-if="emergencyEvents.length === 0" class="empty-state">
        <u-empty text="暂无紧急事件" icon="alert-circle" mode="list" />
      </view>
      
      <view v-else class="event-list">
        <view 
          v-for="event in emergencyEvents" 
          :key="event.id"
          class="event-card"
          @click="goToEventDetail(event.id)"
        >
          <view class="event-header">
            <text class="event-title">{{ event.title }}</text>
            <u-tag 
              :text="getSeverityText(event.severity)" 
              :type="getSeverityType(event.severity)" 
              size="mini"
            />
          </view>
          <view class="event-content">
            <text class="event-location">{{ event.location }}</text>
            <text class="event-time">{{ formatTime(event.eventTime) }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getSecurityStatistics, getSecurityPatrolByUserId, getSecurityEventPage } from '@/api/security'
import ServiceCard from '@/components/ServiceCard.vue'
import { useAuthStore } from '@/store/auth'

// 响应式数据
const statistics = ref({})
const todayPatrols = ref([])
const emergencyEvents = ref([])
const loading = ref(false)

// 获取认证store
const authStore = useAuthStore()

// 计算属性：获取当前用户ID
const currentUserId = computed(() => {
  return authStore.userId || authStore.userInfo?.id
})

// 页面加载时获取数据
onMounted(() => {
  loadStatistics()
  loadTodayPatrols()
  loadEmergencyEvents()
})

/**
 * 加载统计信息
 */
const loadStatistics = async () => {
  try {
    loading.value = true
    const response = await getSecurityStatistics()
    if (response.success && response.data) {
      statistics.value = response.data
    }
  } catch (error) {
    console.error('加载统计信息失败:', error)
    uni.showToast({
      title: '加载统计信息失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

/**
 * 加载今日巡逻
 */
const loadTodayPatrols = async () => {
  try {
    // 检查用户ID是否存在
    if (!currentUserId.value) {
      console.warn('用户ID不存在，跳过加载今日巡逻')
      return
    }
    
    const today = new Date().toISOString().split('T')[0]
    const response = await getSecurityPatrolByUserId(currentUserId.value, today, today)
    if (response.success && response.data) {
      todayPatrols.value = response.data.slice(0, 3) // 只显示前3个巡逻
    }
  } catch (error) {
    console.error('加载今日巡逻失败:', error)
    uni.showToast({
      title: '加载今日巡逻失败',
      icon: 'none'
    })
  }
}

/**
 * 加载紧急事件
 */
const loadEmergencyEvents = async () => {
  try {
    const response = await getSecurityEventPage({
      pageNum: 1,
      pageSize: 3,
      severity: 3 // 紧急事件
    })
    if (response.success && response.data) {
      emergencyEvents.value = response.data.records || []
    }
  } catch (error) {
    console.error('加载紧急事件失败:', error)
    uni.showToast({
      title: '加载紧急事件失败',
      icon: 'none'
    })
  }
}

/**
 * 获取状态文本
 */
const getStatusText = (status) => {
  const statusMap = {
    1: '进行中',
    2: '已完成',
    3: '异常中断'
  }
  return statusMap[status] || '未知状态'
}

/**
 * 获取状态类型
 */
const getStatusType = (status) => {
  const typeMap = {
    1: 'primary',
    2: 'success',
    3: 'error'
  }
  return typeMap[status] || 'info'
}

/**
 * 获取严重程度文本
 */
const getSeverityText = (severity) => {
  const severityMap = {
    1: '一般',
    2: '重要',
    3: '紧急'
  }
  return severityMap[severity] || '未知'
}

/**
 * 获取严重程度类型
 */
const getSeverityType = (severity) => {
  const typeMap = {
    1: 'info',
    2: 'warning',
    3: 'error'
  }
  return typeMap[severity] || 'info'
}

/**
 * 格式化时间
 */
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

/**
 * 获取持续时间
 */
const getDuration = (startTime, endTime) => {
  if (!startTime) return '未开始'
  if (!endTime) return '进行中'
  
  const start = new Date(startTime)
  const end = new Date(endTime)
  const duration = Math.floor((end - start) / (1000 * 60)) // 分钟
  
  if (duration < 60) {
    return `${duration}分钟`
  } else {
    const hours = Math.floor(duration / 60)
    const minutes = duration % 60
    return `${hours}小时${minutes}分钟`
  }
}

// 页面导航方法
const goToRouteManagement = () => {
  uni.navigateTo({
    url: '/pages/property-work/security-management/route-management'
  })
}

const goToPatrolManagement = () => {
  uni.navigateTo({
    url: '/pages/property-work/security-management/patrol-management'
  })
}

const goToEventManagement = () => {
  uni.navigateTo({
    url: '/pages/property-work/security-management/event-management'
  })
}

const goToVisitorManagement = () => {
  uni.navigateTo({
    url: '/pages/property-work/security-management/visitor-management'
  })
}

const goToStatistics = () => {
  uni.navigateTo({
    url: '/pages/property-work/security-management/statistics'
  })
}

const goToPatrolDetail = (patrolId) => {
  uni.navigateTo({
    url: `/pages/property-work/security-management/patrol-detail?id=${patrolId}`
  })
}

const goToEventDetail = (eventId) => {
  uni.navigateTo({
    url: `/pages/property-work/security-management/event-detail?id=${eventId}`
  })
}
</script>

<style lang="scss" scoped>
.security-management-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.statistics-section {
  padding: 20rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  
  .statistics-card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 16rpx;
    padding: 30rpx;
    display: flex;
    justify-content: space-around;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
    
    .statistics-item {
      text-align: center;
      
      .statistics-value {
        display: block;
        font-size: 36rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .statistics-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.function-section {
  padding: 20rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 20rpx;
  }
}

.today-patrols-section, .emergency-events-section {
  padding: 0 20rpx 20rpx;
  
  .section-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 20rpx;
    
    .more-link {
      font-size: 26rpx;
      color: #666;
    }
  }
  
  .empty-state {
    padding: 60rpx 0;
  }
  
  .patrol-list, .event-list {
    .patrol-card, .event-card {
      background: white;
      border-radius: 12rpx;
      padding: 24rpx;
      margin-bottom: 16rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.98);
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
      }
      
      .patrol-header, .event-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12rpx;
        
        .patrol-route, .event-title {
          font-size: 28rpx;
          font-weight: 600;
          color: #333;
        }
      }
      
      .patrol-content, .event-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .patrol-time, .event-location {
          font-size: 24rpx;
          color: #666;
        }
        
        .patrol-duration, .event-time {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }
}
</style>
